﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMS.HelperClasses;
using WHMS.EntityClasses;
using WHMS.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace WMS
{
	public partial class MoveItemsToJunkForm : Form
	{
		DataMngrFormBase<TransactionItemEntity> _tranItemsForm;
		List<ErrorProvider> _errorProviders;

		public MoveItemsToJunkForm()
		{
			InitializeComponent();
		}

		private void MoveItemsForm_Load(object sender, EventArgs e)
		{
			LoadData();

			_errorProviders = new List<ErrorProvider>();

			//ResetTransactionItems();
		}

		void LoadData()
		{
			FormsHelper.LoadComboBox(StoresDDL, StoreFields.Id, StoreFields.Name, () => Business.GetStoresForKeeper());
			FormsHelper.LoadComboBox(ToStoresDDL, StoreFields.Id, StoreFields.Name, () => Business.GetJunkStoresForKeeper());
			FormsHelper.LoadComboBox(ProjectsDDL, ProjectFields.Id, ProjectFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, null));

			FormsHelper.CheckStoresAndProjects(StoresDDL.Items, ProjectsDDL.Items, new List<Control>() { _transItemsGrid, SaveBtn }, NoStoresLbl, NoProjectsLbl);
		}

		private void SaveBtn_Click(object sender, EventArgs e)
		{
			if (!ValidateForm())
				return;

			var transaction = new TransactionEntity()
			{
				ProjectId = (int)ProjectsDDL.SelectedValue,
				PermitNumber = PermitNumberTB.Text,
				CreatedBy = UserInfo.UserId,
				Date = MoveDateDTP.Value.Date,
				Type = "Move"
			};

			var transfer = new TransferTransactionEntity()
			{
				//Transaction = transaction,
				Type = "Junk",
				FromStoreId = (int)StoresDDL.SelectedValue,
				ToStoreId = (int)ToStoresDDL.SelectedValue,
			};

			if (Business.MoveItems(GetSelectedStoreId(), GetSelectedToStoreId(), transfer, transaction, Business.GetGenericCollection<TransactionItemEntity>(_transItems)))//DALHelper.SaveEntity(withdrawl, true))
			{
				MessageBox.Show("تم الحفظ بنجاح.");

				ResetTransactionItems();
			}
		}
		
		private bool ValidateForm()
		{
			var isValid = true;

			var controls = new List<TextBox>();
			controls.Add(PermitNumberTB);

			if (_errorProviders == null)
			{
				_errorProviders = new List<ErrorProvider>();
			}
			else
			{
				foreach (var errorProvider in _errorProviders)
				{
					errorProvider.Clear();
					errorProvider.Dispose();
				}
			}
			foreach (var tb in controls)
			{
				if (string.IsNullOrEmpty(tb.Text.Trim()))
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(tb, "يجب إدخال قيمة");
					errorProvider.RightToLeft = true;

					isValid = false;
					continue;
				}
			}

			if (!ValidatePermitNumber())
				isValid = false;

			_tranItemsForm.ValidateCollection();

			if (_transItems.Count <= 0)
			{
				isValid = false;
				MessageBox.Show("يجب إضافة أصناف", "خطأ فى الحفظ", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return isValid;
		}

		private void StoresDDL_SelectedIndexChanged(object sender, EventArgs e)
		{
			ResetTransactionItems();

			if (StoresDDL.SelectedItem == null)
				return;

			//GetSourceShelves(null);
			GetTargetShelves(null);
		}
		private void ToStoresDDL_SelectedIndexChanged(object sender, EventArgs e)
		{
			ResetTransactionItems();

			if (ToStoresDDL.SelectedItem == null)
				return;

			GetTargetShelves(null);
		}

		private void GetTargetShelves(RelationPredicateBucket filter)
		{
			if (GetSelectedStoreId() == GetSelectedToStoreId())
				return;

			if (filter == null)
				filter = new RelationPredicateBucket();

			var storeId = GetSelectedToStoreId();
			//var fromStoreId = GetSelectedStoreId();
			_toShelves.Clear();

			filter.PredicateExpression.Add(ShelfFields.StoreId == storeId);

			DALHelper.FetchCollection(_toShelves, filter);
		}
		
		private void ResetTransactionItems()
		{
			if (_tranItemsForm != null)
			{
				_tranItemsForm.Dispose();
				_tranItemsForm = null;
			}

			var label = new Label();
			_tranItemsForm = new DataMngrFormBase<TransactionItemEntity>(_transItems, _transItemsGrid, _itemsBS, new Button(), label, label, new RelationPredicateBucket(TransactionItemFields.TransactionId == 0));
			_tranItemsForm.SetNumericFields(new List<int> {3});
			_tranItemsForm.RaiseSelectedChangedEventForComboBoxColumns(new List<int> { 0, 1 });
			_tranItemsForm.SetMandatoryFields(new List<int>() { 0, 1, 2, 3, 4 });
			_tranItemsForm.ComboboxColumnSelectionChanged += new DataMngrFormBase<TransactionItemEntity>.RaiseComboboxColumnSelectionChanged(_tranItemsForm_ComboboxColumnSelectionChanged);
			_tranItemsForm.RowValidating += new DataMngrFormBase<TransactionItemEntity>.RaiseRowValidating(_tranItemsForm_RowValidating);
		}

		void _tranItemsForm_RowValidating(int rowIndex, ref bool hasErrors)
		{
			var requestedQuantityCell = _transItemsGrid.Rows[rowIndex].Cells[3];
			var availableQuantity = _transItemsGrid.Rows[rowIndex].Cells[2].Value;
			var requestedQuantity = requestedQuantityCell.Value;

			if (availableQuantity == null || requestedQuantity == null)
				return;

			if ((decimal)requestedQuantity <= 0)
			{
				requestedQuantityCell.ErrorText = "الكمية المطلوبة يجب أن تكون رقم موجب.";
				hasErrors = true;
				return;
			}

			if ((decimal)availableQuantity >= (decimal)requestedQuantity)
			{
				requestedQuantityCell.ErrorText = string.Empty;
				return;
			}

			requestedQuantityCell.ErrorText = "الكمية المطلوبة يجب أن لا تتعدى الكمية المتاحة.";
			hasErrors = true;
		}

		void _tranItemsForm_ComboboxColumnSelectionChanged(object selectedValue)
		{
			if (selectedValue == null)
				return;

			if (selectedValue is int)
			{
				if (_transItemsGrid.CurrentCell.ColumnIndex == 1)
				{
					var itemId = (int)_transItemsGrid.CurrentRow.Cells[0].Value;
					var shelfId = (int)selectedValue;

					_transItemsGrid.CurrentRow.Cells[2].Value = Business.GetItemBalance(GetSelectedProjectId(), GetSelectedStoreId(), shelfId, itemId, false);

					//if (GetSelectedStoreId() == GetSelectedToStoreId())
					//{						
					//    GetTargetShelves(new RelationPredicateBucket(ShelfFields.Id != shelfId));
					//}
				}
			}
		}

		private int GetSelectedStoreId()
		{
			if (StoresDDL.SelectedItem == null)
				return 0;

			return (int)((System.Data.DataRowView)(StoresDDL.SelectedItem)).Row.ItemArray[0];
		}
		private int GetSelectedToStoreId()
		{
			if (ToStoresDDL.SelectedItem == null)
				return 0;

			return (int)((System.Data.DataRowView)(ToStoresDDL.SelectedItem)).Row.ItemArray[0];
		}
		private int GetSelectedProjectId()
		{
			return (int)((System.Data.DataRowView)(ProjectsDDL.SelectedItem)).Row.ItemArray[0];
		}

		private void ProjectsDDL_SelectedIndexChanged(object sender, EventArgs e)
		{
			var projectId = (int)((System.Data.DataRowView)(ProjectsDDL.SelectedItem)).Row.ItemArray[0];

			Business.GetItemsPlannedForProject(projectId, _items);
		}

		private void _transItemsGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0)
				return;

			if (e.ColumnIndex == 0)
			{
				var control = (_transItemsGrid[1, e.RowIndex] as DataGridViewComboBoxCell);
				LoadShelves(control);
			}
			else if (e.ColumnIndex == 1)
			{
				var control = (_transItemsGrid[4, e.RowIndex] as DataGridViewComboBoxCell);
				LoadTargetShelves(control);				
			}
		}

		#region shelves
		private void LoadTargetShelves(DataGridViewComboBoxCell control)
		{
			control.DisplayMember = ShelfFields.Code.Name;
			control.ValueMember = ShelfFields.Id.Name;			

			var storeId = GetSelectedToStoreId();
			var fromStoreId = GetSelectedStoreId();
			var fromShelfId = (int)_transItemsGrid.CurrentRow.Cells[1].Value;

			var filter = new RelationPredicateBucket();
			filter.PredicateExpression.Add(ShelfFields.StoreId == storeId);
			if(storeId == fromStoreId)
				filter.PredicateExpression.Add(ShelfFields.Id != fromShelfId);

			var shelves = new EntityCollection<ShelfEntity>();
			DALHelper.FetchCollection(shelves, filter);


			var bindingsource = new BindingSource();
			bindingsource.DataSource = shelves;
			control.DataSource = bindingsource;
		}
		private void LoadShelves(DataGridViewComboBoxCell control)
		{
			var itemIdValue = _transItemsGrid.CurrentRow.Cells[0].Value;
			if (itemIdValue == null)
				return;

			control.DisplayMember = ShelfFields.Code.Name;
			control.ValueMember = ShelfFields.Id.Name;

			var shelves = GetShelves((int)itemIdValue);
			var bindingsource = new BindingSource();
			bindingsource.DataSource = shelves;
			control.DataSource = bindingsource;

			if (shelves.Count <= 0)
			{
				MessageBox.Show("لا يوجد رصيد بالمخزن المختار", "تنبيه", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}
		private void GetShelves(RelationPredicateBucket filter)
		{
			if (filter == null)
				filter = new RelationPredicateBucket();

			var storeId = GetSelectedStoreId();
			_shelves.Clear();

			filter.PredicateExpression.Add(ShelfFields.StoreId == storeId);
			DALHelper.FetchCollection(_shelves, filter);

			if (_shelves.Count <= 0)
			{
				MessageBox.Show("لا يوجد رصيد بالمخزن المختار", "تنبيه", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}
		private EntityCollection<ShelfEntity> GetShelves(int itemId)
		{
			var filter = GetShelvesFilter(itemId);


			var shelves = new EntityCollection<ShelfEntity>();
			DALHelper.FetchCollection(shelves, filter);
			return shelves;
		}
		private RelationPredicateBucket GetShelvesFilter(int itemId)
		{
			var shelfFilter = new PredicateExpression(StoreShelfBalanceFields.ItemId == itemId);
			shelfFilter.Add(StoreShelfBalanceFields.StoreId == GetSelectedStoreId());

			var projectFilter = new PredicateExpression(StoreShelfBalanceFields.ProjectId == GetSelectedProjectId());
			shelfFilter.Add(projectFilter);

			var filter = new RelationPredicateBucket(new FieldCompareSetPredicate(ShelfFields.Id, null, StoreShelfBalanceFields.ShelfId, null, SetOperator.In, shelfFilter));
			filter.PredicateExpression.Add(ShelfFields.StoreId == GetSelectedStoreId());
			return filter;
		}
		#endregion

		private bool ValidatePermitNumber()
		{
			return FormsHelper.ValidatePermitNumber(this, PermitNumberTB, _errorProviders, "Move");
		}

		private void PermitNumberTB_Leave(object sender, EventArgs e)
		{
			ValidatePermitNumber();
		}

		private void _transItemsGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.ColumnIndex != quantityDataGridViewTextBoxColumn.Index)
				return;

			var itemIdValue = _transItemsGrid.Rows[e.RowIndex].Cells[itemIdDataGridViewTextBoxColumn.Index].Value;
			if (itemIdValue == null)
				return;

			var form = new UnitConverterForm((int)itemIdValue);
			if (form.ShowDialog() == DialogResult.OK)
			{
				_transItemsGrid.SuspendLayout();
				_transItemsGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.Value;
				_transItemsGrid.UpdateCellValue(e.ColumnIndex, e.RowIndex);
				_transItemsGrid.ResumeLayout(true);
			}
		}
	}
}
